#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <strings.h>

void Usage(std::string proc)
{
    std::cout << "usage:" << proc << ' ' << "ip" << ' ' << "port" << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }
    std::string ip(argv[1]);
    uint16_t port = std::atoi(argv[2]);
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        perror("socket create false");
        exit(1);
    }
    struct sockaddr_in sever;
    bzero(&sever, sizeof(sever));
    sever.sin_family = AF_INET;
    sever.sin_port = htons(port);
    sever.sin_addr.s_addr = inet_addr(ip.c_str());

    // 直接通信
    while (true)
    {
        std::string message;
        std::cout << "please enter# ";
        std::getline(std::cin, message);
        // std::cout<<"已输入:"<<message<<std::endl;
        //  发消息                    这里要传message.size()+1是因为字符串末尾还有'\0'
        sendto(sockfd, message.c_str(), message.size() + 1, 0, (struct sockaddr *)&sever, sizeof(sever));
        // 收消息
        struct sockaddr_in peer;
        bzero(&peer, sizeof(peer));
        char buffer[1024];
        socklen_t adderlen = sizeof(peer);
        ssize_t n = recvfrom(sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&peer, &adderlen);
        if (n > 0)
        {
            buffer[n] = '\0';
            std::cout << buffer << std::endl;
        }
    }
    return 0;
}
